import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-forget',
  templateUrl: './forget.component.html',
  styleUrls: ['./forget.component.scss']
})
export class ForgetComponent implements OnInit {

  form: FormGroup = new FormGroup({});
  passwordVisible = false;

  get username() {
    return this.form.get('username');
  }
  get phone() {
    return this.form.get('phone');
  }
  get code() {
    return this.form.get('code');
  }
  get password() {
    return this.form.get('password');
  }


  constructor(
    private router: Router,
    private fb: FormBuilder,
  ) { }

  goToLogin(): void {
    this.router.navigate(['/auth', 'login']);
  }

  ngOnInit(): void {
    this.form = this.fb.group({
      username: ['', {
        validators: [
          (c: AbstractControl) => {
            return !c.value ? { required: 'auth.username_error_required' } : null;
          },
        ]
      }],
      phone: ['', {
        validators: [
          (c: AbstractControl) => {
            return !c.value ? { required: 'auth.phone_error_required' } : null;
          },
        ]
      }],
      code: ['', {
        validators: [
          (c: AbstractControl) => {
            return !c.value ? { required: 'auth.code_error_required' } : null;
          },
        ]
      }],
      password: ['', {
        validators: [
          (c: AbstractControl) => {
            return !c.value ? { required: 'auth.password_error_required' } : null;
          },
        ]
      }],
    });
  }

  onSubmit(): void {
    for (const i in this.form.controls) {
      if (this.form.controls.hasOwnProperty(i)) {
        this.form.controls[i].markAsDirty();
        this.form.controls[i].updateValueAndValidity();
      }
    }
  }

  setErrorTip(name: string): string {
    let msg = ''; let errors: any;
    if (name === 'username') {
      errors = this.username?.errors;
    } else if (name === 'password') {
      errors = this.password?.errors;
    } else if (name === 'phone') {
      errors = this.phone?.errors;
    } else if (name === 'code') {
      errors = this.code?.errors;
    }
    if (errors) {
      for (const key in errors) {
        if (Object.prototype.hasOwnProperty.call(errors, key)) {
          msg = !msg ? errors[key] : msg;
        }
      }
    }
    return msg;
  }

}
